<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="title"
    :close-on-click-modal="false"
    width="600px"
    @close="close"
  >
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules" label-width="110px">
      <el-form-item label="所属门店：" prop="shopId">
        <el-select v-model="form.shopId" placeholder="请选择">
          <el-option
            v-for="item in $store.state.user.manageShopList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="终端名称：" prop="deviceName">
        <el-input v-model="form.deviceName" placeholder="请输入" />
      </el-form-item>

      <el-form-item v-if="form.kdDeviceNo" label="终端编号：">
        {{ form.kdDeviceNo }}
      </el-form-item>

      <el-form-item label="第三方编号：" prop="outDeviceNo">
        <el-input v-model.trim="form.outDeviceNo" placeholder="请输入" />
      </el-form-item>

      <el-form-item label="秘钥：" prop="secretKey">
        <el-input v-model.trim="form.secretKey" :autosize="{ minRows: 2, maxRows: 6}" maxlength="200" show-word-limit type="textarea" placeholder="请输入" />
      </el-form-item>

      <el-form-item label="备注：" prop="description">
        <el-input v-model="form.description" placeholder="说明备注" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button size="small" round @click="hide">取 消</el-button>
      <el-button size="small" round type="primary" @click="handleSubmit('form')">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { validateDeviceNo, validateStrLen } from '@/utils/validate.js'
import { addDevice, updateDevice } from '@/api/business'

export default {
  props: {
    scope: {
      require: true,
      type: Number
    },
    shopId: {
      require: true,
      type: Number
    }
  },
  data() {
    // 终端名称
    const validateDEVICENOName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('终端名称'))
      } else if (!validateStrLen(value, 64)) {
        callback(new Error('长度不超过20个汉字或40个字符'))
      } else {
        callback()
      }
    }
    // 终端编号
    const validateOutDeviceNo = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!validateDeviceNo(value)) {
        callback(new Error('编号只可以是数字或者英文'))
      } else {
        callback()
      }
    }
    // 备注
    const validateDescription = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!validateStrLen(value, 30)) {
        callback(new Error('长度不超过15个汉字或30个字符'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        shopId: [
          {
            required: true,
            message: '请选择组织架构',
            trigger: ['change']
          }
        ],
        secretKey: [
          {
            required: false,
            message: '请输入秘钥',
            trigger: ['change']
          },
          { min: 10, max: 200, message: '长度大于等于 10 个字符', trigger: ['blur', 'change'] }
        ],
        deviceName: [
          {
            required: true,
            validator: validateDEVICENOName,
            trigger: ['blur', 'change']
          }
        ],
        outDeviceNo: [
          {
            validator: validateOutDeviceNo,
            trigger: ['blur', 'change']
          }
        ],
        description: [
          {
            validator: validateDescription,
            trigger: ['blur', 'change']
          }
        ]
      },
      title: null,
      resolve: null,
      loading: false,
      reject: null,
      mode: null,
      dialogVisible: null,
      // allShopList: [],
      form: {
        shopId: '',
        deviceName: '',
        outDeviceNo: '',
        secretKey: '',
        description: ''
      }
    }
  },
  methods: {
    openAdd() {
      this.mode = 'add'
      this.title = '新增终端'
      this.form.shopId = this.shopId !== -1 ? this.shopId : 0
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    openEdit(row) {
      this.title = '编辑终端'
      this.mode = 'edit'
      const data = Object.assign({}, row)
      this.form = data
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    close() {
      this.form = {
        shopId: '',
        deviceName: '',
        outDeviceNo: '',
        secretKey: '',
        description: ''
      }
      this.loading = false
      this.$refs.form.resetFields()
    },

    show() {
      this.dialogVisible = true
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    updateObject() {
      const data = {}
      data.deviceName = this.form.deviceName
      data.outDeviceNo = this.form.outDeviceNo
      data.description = this.form.description
      data.shopId = this.form.shopId
      data.id = this.form.id
      this.loading = true
      return updateDevice(this.form)
        .then(res => {
          this.loading = false
          if (res.code === 0) {
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
            this.$store.dispatch('GetManageDevice')
            this.resolve && this.resolve()
            this.hide()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {
          this.loading = false
        })
    },

    addObject() {
      const data = Object.assign({}, this.form)
      // data["shopId"] = this.shopId;
      this.loading = true
      return addDevice(data)
        .then(res => {
          this.loading = false
          if (res.code === 0) {
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
            this.$store.dispatch('GetManageDevice')
            this.resolve && this.resolve()
            this.hide()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {
          this.loading = false
        })
    },

    handleSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.mode === 'edit') {
            this.updateObject()
          } else {
            this.addObject()
          }
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.el-select {
  width: 100%;
}
</style>
